package ru.ipo.dces.problemsviewer;

import javax.swing.*;
import javax.swing.text.html.HTMLDocument;
import java.awt.*;
import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: ilya
 * Date: 11.06.11
 * Time: 12:26
 */
public class TextStrangeTextPaneBehaviour {

    public static void main(String[] args) throws IOException {
        JComponent c1 = create(fromString("asdf <b>asdf</b>"));
        JComponent c2 = create(fromString("pqrs <b>pqrs</b>"));

        JFrame f = new JFrame();
        f.setLayout(new GridLayout(1, 2));
        f.add(c1);
        f.add(c2);

        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }

    private static InputStream fromString(String s) throws UnsupportedEncodingException {
        return new ByteArrayInputStream(s.getBytes("UTF-8"));
    }

    public static JComponent create(InputStream statement) throws IOException {
        File baseDir = getTemporaryFolder();

        JTextPane pane = new JTextPane();
        pane.setEditable(false);
        pane.setDisabledTextColor(Color.BLACK);
        pane.setFocusable(false);
        pane.setContentType("text/html; charset=UTF-8");

        //TODO try to rewrite document creation as in http://www.javaworld.com/javatips/jw-javatip109.html?page=1
        //TODO think of base URL with kio-problem protocol (cf. jar-jar protocol somewhere in KIO-API)
        pane.read(statement, "statement");

        HTMLDocument doc = (HTMLDocument) pane.getDocument();
        System.out.println(pane.getContentType());
        doc.setBase(baseDir.toURI().toURL());
        return new JScrollPane(pane);
    }

    private static File getTemporaryFolder() {
        try {
            File tmp = File.createTempFile("problem_test", "_tmp");
            if (!tmp.delete())
                return null;
            return tmp;
        } catch (IOException e) {
            return null;
        }
    }

}
